﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using StevensReceipts.Domain;
using StevensReceipts.Repository;
using StevensReceipts.Web.Models;
using StevensReceipts.Web.Models.ViewModels;
using WebMatrix.WebData;

namespace StevensReceipts.Web.Controllers
{
    public class ControllerBase : Controller
    {
        public UserSession UserSession { get; set; }
    }

    public class UserSession
    {
        public int CurrentBusinessId { get; set; }
        public bool IsLoggedIn { get; set; }
        public int Username { get; set; }
    }

    public class SetupController : ControllerBase
    {
        //private  IRepository<Business> _bussinessRepository;

        private IReceiptsDataSource _unitOfWork;
        public SetupController(IReceiptsDataSource uow)
        {
            _unitOfWork = uow;
            if(WebSecurity.IsAuthenticated)
            {
                UserSession.IsLoggedIn = true;
                UserSession.Username = WebSecurity.CurrentUserId;
            }
        }

        [HttpGet]
        public RedirectToRouteResult Welcome(int? id)
        {
            if(id == null)
            {
                return RedirectToAction("Start","Setup");
            }
            return RedirectToAction("EditDetails", "Setup", new { businessId = id });
        }

        [HttpGet]
        public ActionResult Start()
        {
            var countryList = GetCountries();
            ViewBag.Countries = countryList;
            return View();
        }

        [HttpPost]
        public ActionResult Start(BusinessStartViewModel viewModel)
        {
             if(ModelState.IsValid)
            {
                var business = new Business
                                   {
                                       BusinessName = viewModel.BusinessName, 
                                       BusinessCountry = viewModel.Country
                                   };
                Business biz = _unitOfWork.Businesses.Add(business);


                _unitOfWork.Save();
                int bizId = biz.Id;
                return RedirectToAction("EditDetails", "Setup", new { businessId = bizId }
                    );
            }

            var countryList = GetCountries();
            ViewBag.Countries = countryList;
            return View();
        }

        private SelectList GetCountries()
        {
            IEnumerable<string> countries =  new List<string> {"New Zealand", "Australia", "Canada", "United States"};
            var list = new SelectList(countries);
            return list;
        }
        [HttpGet]
        public ActionResult EditDetails(int businessId)
        {
            
            var business = _unitOfWork
                            .Businesses
                            .GetSingle(b => b.Id == businessId);

            var businessDetails = LoadBusinessDetailsViewModelFromBusiness(business);


            return View(businessDetails);
        }

        private BusinessDetailsViewModel LoadBusinessDetailsViewModelFromBusiness(Business business)
        {
            var viewModel = new BusinessDetailsViewModel
                                {
                                    Id = business.Id,
                                    BusinessName = business.BusinessName,
                                    BusinessType = business.Type,
                                    DescriptionLine = business.BusinessLine,
                                    Fax = business.Fax,
                                    LegalName = business.TradingName,
                                    Mobile = business.Mobile,
                                    PhysicalAddress = business.PhysicalAddress,
                                    PostalAddress = business.PostalAddress,
                                    Telephone = business.Telephone
                                };
            return viewModel;
        }

        [HttpPost]
        public ActionResult EditDetails(BusinessDetailsViewModel viewModel)
        {
            if(ModelState.IsValid)
            {
                

                var business = _unitOfWork.Businesses.GetSingle(b => b.Id == viewModel.Id);


                business.TradingName = viewModel.LegalName;
                business.Type = viewModel.BusinessType;
                business.BusinessLine = viewModel.DescriptionLine;
                business.BusinessName = viewModel.BusinessName;
                if (string.IsNullOrWhiteSpace(viewModel.PhysicalAddress.AddressLine1) || 
                    string.IsNullOrWhiteSpace(viewModel.PhysicalAddress.Suburb) || 
                    string.IsNullOrWhiteSpace(viewModel.PhysicalAddress.City))
                {
                    business.PhysicalAddress = null;
                }
                if (string.IsNullOrWhiteSpace(viewModel.PostalAddress.AddressLine1) ||
                    string.IsNullOrWhiteSpace(viewModel.PostalAddress.Suburb) ||
                    string.IsNullOrWhiteSpace(viewModel.PostalAddress.City))
                {
                    business.PostalAddress = null;
                }
                if (business.PhysicalAddress == null)
                    business.PhysicalAddress = viewModel.PhysicalAddress;
                else
                {
                    business.PhysicalAddress.AddressLine1 = viewModel.PhysicalAddress.AddressLine1;
                    business.PhysicalAddress.Suburb = viewModel.PhysicalAddress.Suburb;
                    business.PhysicalAddress.City = viewModel.PhysicalAddress.City;
                    business.PhysicalAddress.Country = viewModel.PhysicalAddress.Country;
                    business.PhysicalAddress.PostCode = viewModel.PhysicalAddress.PostCode;
                    business.PhysicalAddress.Modified = DateTime.Now;
                }
                if(business.PostalAddress == null)
                    business.PostalAddress = viewModel.PostalAddress;
                else
                {
                    business.PostalAddress.AddressLine1 = viewModel.PostalAddress.AddressLine1;
                    business.PostalAddress.Suburb = viewModel.PostalAddress.Suburb;
                    business.PostalAddress.City = viewModel.PostalAddress.City;
                    business.PostalAddress.Country = viewModel.PostalAddress.Country;
                    business.PostalAddress.PostCode = viewModel.PostalAddress.PostCode;
                    business.PostalAddress.Modified = DateTime.Now;
                }
                business.Mobile = viewModel.Mobile;
                business.Telephone = viewModel.Telephone;
                business.Fax = viewModel.Fax;

                _unitOfWork.Businesses.Update(business);
                _unitOfWork.Save();
                return RedirectToAction("EditFinancial", "Setup", new { businessId = viewModel.Id });
            }
            return View(viewModel);
        }

        [HttpGet]
        public ActionResult EditFinancial(int? businessId)
        {
            if (businessId == null)
                RedirectToAction("Welcome", "Setup");
            var business = _unitOfWork.Businesses.GetSingle(b => b.Id == businessId);
                
            EditFinancialViewModel viewModel = LoadEditFinancialViewModelFromBusiness(business);
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult EditFinancial(EditFinancialViewModel viewModel)
        {
            if (viewModel == null || viewModel.BusinessId == 0)
                return RedirectToAction("Welcome", "Setup");

            if(ModelState.IsValid)
            {
                var business = _unitOfWork.Businesses.GetSingle(b => b.Id == viewModel.BusinessId);

                business.FinancialYearEndDay = viewModel.FinancialYearEndDay;
                business.FinancialYearEndMonth = viewModel.FinancialYearEndMonth;
                business.GstRegistered = viewModel.GstRegistered;
                if(viewModel.SelectedGstBasis != GstBasis.None)
                {
                   business.GstNumber = viewModel.GstNumber;
                    business.GstBasis = viewModel.SelectedGstBasis;
                    business.GstPeriod = viewModel.SelectedGstPeriod; 
                }
                
                _unitOfWork.Businesses.Update(business);
                _unitOfWork.Save();

                return RedirectToAction("EditUser", "Setup", new { businessId = viewModel.BusinessId });
            }
            viewModel.Days = Util.Days();
            viewModel.Months = Util.Months();
            return View(viewModel);
        }

        private EditFinancialViewModel LoadEditFinancialViewModelFromBusiness(Business business)
        {
            return new EditFinancialViewModel
                       {
                           BusinessId = business.Id,
                           FinancialYearEndDay = business.FinancialYearEndDay,
                           FinancialYearEndMonth = business.FinancialYearEndMonth,
                           GstNumber = business.GstNumber,
                           SelectedGstBasis = business.GstBasis,
                           SelectedGstPeriod = business.GstPeriod,
                           GstRegistered =  business.GstRegistered,
                           Days = Util.Days(),
                           Months = Util.Months()
                       };
        }

        [HttpGet]
        public ActionResult EditUser(int? businessId)
        {
            var viewModel = new EditUerViewModel();
            return View(viewModel);
        }

        public ActionResult Complete()
        {
            return RedirectToAction("Dashboard", "Home");
        }
    }

}
